import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { ElMessage } from 'element-plus'

const routes = [
  // 公开路由
  {
    path: '/login',
    name: 'Login',
    component: () => import('../components/LoginForm.vue'),
    meta: { requiresAuth: false }
  },
  // 默认路由
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/HomeView.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('../views/PanelView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/UsersView.vue'),
        meta: { requiresAuth: true, adminOnly: true }
      },
      {
        path: '/tickets',
        name: 'Tickets',
        component: () => import('../views/Tickets/index.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/comments',
        name: 'Comments',
        component: () => import('../views/Comments/index.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/orders',
        name: 'Orders',
        component: () => import('../views/Order/index.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'sights',
        name: 'Sights',
        component: () => import('../views/Sight/SightView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/articles',
        name: 'Articles',
        component: () => import('../views/Articles/index.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('../views/admin/SettingsView.vue'),
        meta: { requiresAuth: true, adminOnly: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('../views/admin/ProfileView.vue'),
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth !== false && !authStore.isAuthenticated) {
    // 未认证且访问受保护路由，重定向到登录页
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    // 已认证且访问登录页，重定向到主页
    next('/')
  } else if (to.meta.adminOnly && !authStore.isAdmin) {
      // 需要管理员权限但用户不是管理员
      ElMessage.error('您没有权限访问该页面')
      next(false) // 取消导航
    } else {
      // 其他情况允许访问
      next()
    }
})

export default router